/*
 *   This File is Part of CuteOgre Game Engine
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *	Copyright 2010 Alexandre Pires ( c.alexandre.pires@gmail.com )
 *  Created on: 2010/08/22
 */

#include "GUIManager.h"
#include "LogManager.h"
#include "ConfigManager.h"
#include "Gui/Layout.h"
#include "Gui/StyleSheetManager.h"
#include "OGRE/OgreResourceManager.h"
#include <QStringList>

template<> GUIManager* Singleton<GUIManager>::ms_Singleton = 0;

void GUIManager::init ( ) {

	if ( !mShutdown )
		return;

	LogManager::message("GUIManager::Starting up");

	mStyleSheetManager = new StyleSheetManager();
	mStyleSheetManager->init();

	QString str = ConfigManager::readString ( "LayoutPath", "Data/Layouts;" );

	if ( str.endsWith(';') )
		str.chop(1);

	QStringList urls = str.split ( ';' );

	Ogre::ResourceGroupManager* mngr =
			&Ogre::ResourceGroupManager::getSingleton ();

	foreach ( QString url, urls )
			mngr->addResourceLocation ( url.toStdString(), "FileSystem", "Layouts" );

	mShutdown = false;
}

void GUIManager::shutdown () {

	if ( mShutdown )
		return;

	LogManager::message("GUIManager::Shutting down");

	foreach ( Layout* layout, mLayouts ) {
		delete layout;
	}

	mLayouts.clear();

	mStyleSheetManager->shutdown();

	delete mStyleSheetManager;

	mShutdown = true;

}

void GUIManager::loadLayout ( const QString& rName ) {

	if ( mLayouts.find(rName) != mLayouts.end() ) {
		LogManager::message(QString("GUIManager::Layout %1 already loaded").arg(rName));
		return;
	}

	LogManager::message(QString("GUIManager::Loading layout %1").arg(rName));

	mLayouts[rName] = new Layout( rName );
}

void GUIManager::unloadLayout (  const QString& rName ) {

	if ( mLayouts.find(rName) == mLayouts.end() ) {
		LogManager::message(QString("GUIManager::Layout %1 not loaded").arg(rName));
		return;
	}

	LogManager::message(QString("GUIManager::Unloading layout %1").arg(rName));

	delete mLayouts[rName];
	mLayouts.remove(rName);
}

Layout* GUIManager::getLayout (  const QString& rName ) {

	if ( mLayouts.find(rName) == mLayouts.end() ) {
		LogManager::message(QString("GUIManager::Layout %1 not loaded").arg(rName));
		return 0;
	}

	return mLayouts[rName];
}
